#include <QtGui>
#include <QtDebug>

#include "chatwidget.h"
#include "historywidget.h"
#include "../xmpp/connectionstore.h"
#include "../xmpp/connection.h"
#include "../account.h"
#include "../accountstore.h"
#include "../ui/ui_chat.h"

struct Kajim::ChatWidget::Private
{
    Ui_ChatWidget ui;
    QString peerJid;
    QString peerName;
    QString ownJid;
    QString ownName;
    int accountHandler;
};

Kajim::ChatWidget::ChatWidget(const QString & peerJid, int accountHandler, QWidget * parent)
    : Kajim::Common::ContentContainerWidget(parent)
{
    d = new Private;
    d->ui.setupUi(this);
    d->peerJid = peerJid;
    d->accountHandler = accountHandler;

    Kajim::XMPP::ConnectionStore * connectionStore = Kajim::XMPP::ConnectionStore::instance();
    Kajim::XMPP::Connection * conn = connectionStore->accountConnection(d->accountHandler);

    // connect signals
    connect(d->ui.textLine, SIGNAL(textSent(const QString &)), this, SLOT(textLineActivated(const QString &)));
    connect(this, SIGNAL(sendMessage(const QString &, const QString &, const QString &)),
            conn, SLOT(sendMessage(const QString &, const QString &, const QString &)));

    // initialize data
    reloadAccountData();
}

Kajim::ChatWidget::~ChatWidget()
{
    delete d;
    qDebug() << "Chat widget destroyed";
}

QString Kajim::ChatWidget::title()
{
    return d->peerJid;
}

void Kajim::ChatWidget::receivePeerMessage(const QString & body, const QString & subject)
{
    d->ui.chat->appendUserMessage(d->peerName, d->peerJid, body);
}

void Kajim::ChatWidget::textLineActivated(const QString & text)
{
    if (text.isEmpty()) {
        return;
    }
    // send message to d->peerJid
    emit sendMessage(d->peerJid, text, "");

    // add message to the history
    d->ui.chat->appendUserMessage(d->ownName, d->ownJid, text);
}

/**
 * \brief Reload account data using account handler.
 */
void Kajim::ChatWidget::reloadAccountData()
{
    // get user name
    Kajim::AccountStore * accountStore = Kajim::AccountStore::instance();
    Kajim::Account * account = accountStore->account(d->accountHandler);
    // TODO: add account==0 check
    // TODO: using account name to identify user in the conversation is not a good idea
    d->ownName = account->param("name");

    // get peer name
    Kajim::XMPP::ConnectionStore * connectionStore = Kajim::XMPP::ConnectionStore::instance();
    Kajim::XMPP::Connection * conn = connectionStore->accountConnection(d->accountHandler);
    // TODO: add conn==0 check
    d->peerName = conn->contactName(d->peerJid);
}

